<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/7
 * Time: 15:12
 */

namespace bgb\sms;

use bgb\Http;

class Alidayu {

    use Http;

    protected static $instance;

    protected $accessKeyId;

    protected $accessKeySecret;

    private function __construct($accessKeyId, $accessKeySecret)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
    }

    /**
     * @param $accessKeyId
     * @param $accessKeySecret
     * @return self
     */
    public static function getInstance($accessKeyId, $accessKeySecret)
    {
        $key = 'accessKeyId:' . $accessKeyId . ':accessKeySecret' . $accessKeySecret;
        if (!isset(self::$instance[$key])) {
            self::$instance[$key] = new static($accessKeyId, $accessKeySecret);
        }

        return self::$instance[$key];
    }

    /**
     * 对外发送短信方法
     * @param $phone string|array 接收短信号码
     * @param $signName string 签名
     * @param $templateCode string 模板名称
     * @param array $params 参数
     * @param string $outId 外部标识 可选
     * @return mixed
     */
    public function send($phone, $signName, $templateCode, $params = [], $outId = '')
    {
        return $this->_send($phone, $signName, $templateCode, $params, $outId);
    }

    /**
     * 发送短信
     * @param $phone
     * @param $signName
     * @param $templateCode
     * @param array $params
     * @param string $outId
     * @return mixed
     */
    private function _send($phone, $signName, $templateCode, $params = [], $outId = '')
    {

        is_array($phone) && $phone = implode(',', $phone);

        $data = [
            'PhoneNumbers' => $phone,
            'SignName' => $signName,
            'TemplateCode' => $templateCode,
            'TemplateParam' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'Action' => 'SendSms',
            'Version' => '2017-05-25',
            'RegionID' => 'cn-hangzhou',
            'AccessKeyId' => $this->accessKeyId,
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'Format' => 'JSON',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureVersion' => '1.0',
            'SignatureNonce' => uniqid(),
        ];

        if ($outId) {
            $data['OutId'] = $outId;
        }

        $data['Signature'] = $this->_getSign($data);

        return $this->getRequest('http://dysmsapi.aliyuncs.com/', $data);

    }

    /**
     * 获取签名
     * @param array $params
     * @return string
     */
    private function _getSign(array $params = [])
    {
        ksort($params);

        $paramsString = urlencode(http_build_query($params));

        $paramsString = str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $paramsString);

        $paramsString = 'GET&%2F&' . $paramsString;

        return base64_encode(hash_hmac('sha1', $paramsString, $this->accessKeySecret . '&', true));

    }

}